import { $t } from "@/locales";
import toastIcon from '@/assets/user-logo2x.png';
import { showLoadingToast, showToast } from "vant";
import debounce from 'debounce';

const u = navigator.userAgent
export const isAndroid = u.indexOf('Android') > -1 || u.indexOf('Adr') > -1 //android终端
export const isiOS = !!u.match(/\(i[^;]+;( U;)? CPU.+Mac OS X/) //ios终端
export const isHarmony = u.indexOf('Harmony') > -1;
export const isWeixin = /miniProgram/i.test(u) && /micromessenger/i.test(u);
export const isInWxWb = /micromessenger/i.test(u) || /WeiBo/i.test(u);
export const isInWxWbQQ = /micromessenger/i.test(u) || /WeiBo/i.test(u) || /QQ/i.test(u);
export const REG_USER_NAME = /^[\u4E00-\u9FA5a-zA-Z0-9_-]{4,16}$/;
export const REG_PHONE = /^[1](([3][0-9])|([4][01456789])|([5][012356789])|([6][2567])|([7][0-8])|([8][0-9])|([9][012356789]))[0-9]{8}$/;
export const REG_URL = /(((^https?:(?:\/\/)?)(?:[-;:&=+$,\w]+@)?[A-Za-z0-9.-]+(?::\d+)?|(?:www.|[-;:&=+$,\w]+@)[A-Za-z0-9.-]+)((?:\/[+~%/.\w-_]*)?\??(?:[-+=&;%@.\w_]*)#?(?:[\w]*))?)$/;
export const emojiReg = /[\uD83C|\uD83D|\uD83E][\uDC00-\uDFFF][\u200D|\uFE0F]|[\uD83C|\uD83D|\uD83E][\uDC00-\uDFFF]|[0-9|*|#]\uFE0F\u20E3|[0-9|#]\u20E3|[\u203C-\u3299]\uFE0F\u200D|[\u203C-\u3299]\uFE0F|[\u2122-\u2B55]|\u303D|[\A9|\AE]\u3030|\uA9|\uAE|\u3030/gi;

export function isPureText(str: string) {
  return !/[\uD800-\uDBFF][\uDC00-\uDFFF]|[\uD83C-\uDBFF][\uDC00-\uDFFF]|[\u2600-\u27BF]/g.test(str);
}

export function filterChars(str: string) {
  if (str) {
    return str.replace(/[^a-zA-Z\d\u4e00-\u9fa5\.——@-]/gi, '');
  }
  return '';
}

export function isMobile(val: string) {
  return REG_PHONE.test(val);
}

export function isHttp(url: string) {
  return url.indexOf('http://') !== -1 || url.indexOf('https://') !== -1
}

export function isExternal(path: string) {
  return /^(https?:|mailto:|tel:)/.test(path)
}

export function validURL(url: string) {
  const reg = /^(https?|ftp):\/\/([a-zA-Z0-9.-]+(:[a-zA-Z0-9.&%$-]+)*@)*((25[0-5]|2[0-4][0-9]|1[0-9]{2}|[1-9][0-9]?)(\.(25[0-5]|2[0-4][0-9]|1[0-9]{2}|[1-9]?[0-9])){3}|([a-zA-Z0-9-]+\.)*[a-zA-Z0-9-]+\.(com|edu|gov|int|mil|net|org|biz|arpa|info|name|pro|aero|coop|museum|[a-zA-Z]{2}))(:[0-9]+)*(\/($|[a-zA-Z0-9.,?'\\+&%$#=~_-]+))*$/
  return reg.test(url)
}

export function validEmail(email: string) {
  const reg = /^(([^<>()\[\]\\.,;:\s@"]+(\.[^<>()\[\]\\.,;:\s@"]+)*)|(".+"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/
  return reg.test(email)
}

export function isNumber(checkVal: string) {
  var reg = /^-?[1-9][0-9]?.?[0-9]*$/;
  return reg.test(checkVal);
}

export function isAbsoluteURL(url: string) {
  // A URL is considered absolute if it begins with "<scheme>://" or "//" (protocol-relative URL).
  // RFC 3986 defines scheme name as a sequence of characters beginning with a letter and followed
  // by any combination of letters, digits, plus, period, or hyphen.
  return /^([a-z][a-z\d+\-.]*:)?\/\//i.test(url)
}

export function uuid() {
  const s: any = [];
  const hexDigits = "0123456789abcdef";
  for (let i = 0; i < 36; i++) {
    s[i] = hexDigits.substr(Math.floor(Math.random() * 0x10), 1);
  }
  s[14] = "4"; // bits 12-15 of the time_hi_and_version field to 0010
  s[19] = hexDigits.substr((s[19] & 0x3) | 0x8, 1); // bits 6-7 of the clock_seq_hi_and_reserved to 01
  s[8] = s[13] = s[18] = s[23] = "-";

  const uuid = s.join("");
  return uuid;
}

export function getQueryString(name: string) {
  let reg = new RegExp("(^|&)" + name + "=([^&]*)(&|$)", "i");
  let queryStr = window.location.search;
  if (!queryStr) {
    queryStr = '?' + window.location.href.split('?')[1];
  }
  let r = queryStr.substr(1).match(reg);
  if (r != null) {
    return decodeURIComponent(r[2]);
  };
  return null;
}

export function dateFormat(val: number | string | Date, fmt: string = 'yyyy-MM-dd') {
  if(!val) {
    return '';
  }
  if (typeof val == 'string') {
    if (val.includes('-')) {
      val = val.replace(/-/g, '/');
    }
    if (!val.includes('/')) {
      val = parseInt(val);
    }
  }
  const date = new Date(val);
  var o: any = {
    "M+": date.getMonth() + 1, //月份
    "d+": date.getDate(), //日
    "h+": date.getHours(), //小时
    "m+": date.getMinutes(), //分
    "s+": date.getSeconds(), //秒
    "q+": Math.floor((date.getMonth() + 3) / 3), //季度
    "S": date.getMilliseconds() //毫秒
  };
  if (/(y+)/.test(fmt)) {
    fmt = fmt.replace(RegExp.$1, (date.getFullYear() + "").substr(4 - RegExp.$1.length));
  }
  for (var k in o) {
    if (new RegExp("(" + k + ")").test(fmt)) {
      fmt = fmt.replace(RegExp.$1, (RegExp.$1.length == 1) ? (o[k]) : (("00" + o[k]).substr(("" + o[k]).length)));
    }
  }
  return fmt;
}

export function jsonParseItem(name: string, parse: boolean = true): any {
  let data = sessionStorage.getItem(name);
  if (!data || data == 'null' || data == 'undefined') {
    data = localStorage.getItem(name);
    if (!data || data == 'null' || data == 'undefined') {
      data = localStorage.getItem(name);
      return null;
    }
  }
  if (parse) {
    try {
      return JSON.parse(data);
    } catch (e: any) {
      return data;
    }
  } else {
    return data;
  }
}

export async function getHtmlBuildTime() {
  const res = await fetch(`${location.origin}/index.html?t=${Date.now()}`);
  const html = await res.text();
  const match = html.match(/<meta name="buildTime" content="(.*)">/);
  const buildTime = match?.[1] || '';
  return buildTime;
}

export function validatePassword(pwd: any) {
  const hasNumber = /\d+/;
  const hasLetter = /[a-zA-Z]+/;
  const startLetter = /^[a-zA-Z]/;
  // 特殊字符右后端检验
  // const hasSpecial = /[~!@#$%^&*)(_+}{|:?><\[\]`\-=,\\\'\"\.]+/;
  return hasNumber.test(pwd) && hasLetter.test(pwd) && startLetter.test(pwd);
}

export function getDistance(lnglat1: { lng: any, lat: any }, lnglat2: { lng: any, lat: any }) {
  const lat1 = lnglat1.lat || 0;
  const lng1 = lnglat1.lng || 0;
  const lat2 = lnglat2.lat || 0;
  const lng2 = lnglat2.lng || 0;

  const rad1 = lat1 * Math.PI / 180.0;
  const rad2 = lat2 * Math.PI / 180.0;
  const a = rad1 - rad2;
  const b = lng1 * Math.PI / 180.0 - lng2 * Math.PI / 180.0;
  const r = 6378137;
  const distance = r * 2 * Math.asin(Math.sqrt(Math.pow(Math.sin(a / 2), 2) + Math.cos(rad1) * Math.cos(rad2) * Math.pow(Math.sin(b / 2), 2)));
  // 返回计算好的距离（m单位）
  return distance;
}

export function fileToBase64(file: any) {
  return new Promise((resolve, reject) => {
    // 创建一个新的 FileReader 对象
    const reader: any = new FileReader();
    // 读取 File 对象
    reader.readAsDataURL(file);
    // 加载完成后
    reader.onload = function () {
      // 将读取的数据转换为 base64 编码的字符串
      const base64String = reader.result.split(",")[1];
      // 解析为 Promise 对象，并返回 base64 编码的字符串
      resolve(base64String);
    };
    // 加载失败时
    reader.onerror = function () {
      reject(new Error("Failed to load file"));
    };
  });
}

export const showLoading = debounce(function () {
  return showLoadingToast({
    duration: 30000,
    icon: toastIcon,
    forbidClick: true,
    message: $t('common.loading')
  })
}, 1200, {
  immediate: true
});

export function loadScript(src: string) {
  return new Promise((resolve, reject) => {
    const script = document.createElement('script');
    script.type = "text/javascript";
    script.src = src;
    script.onerror = reject;
    script.onload = resolve;
    document.head.appendChild(script);
  });
}

//获得角度
export function getAngle(angx: number, angy: number) {
  return Math.atan2(angy, angx) * 180 / Math.PI;
};

//根据起点终点返回方向 1向上 2向下 3向左 4向右 0未滑动
export function getDirection(startx: number, starty: number, endx: number, endy: number) {
  var angx = endx - startx;
  var angy = endy - starty;
  var result = 0;

  //如果滑动距离太短
  if (Math.abs(angx) < 60 && Math.abs(angy) < 60) {
    return result;
  }

  var angle = getAngle(angx, angy);
  if (angle >= -135 && angle <= -45) {
    result = 1;
  } else if (angle > 45 && angle < 135) {
    result = 2;
  } else if ((angle >= 135 && angle <= 180) || (angle >= -180 && angle < -135)) {
    result = 3;
  } else if (angle >= -45 && angle <= 45) {
    result = 4;
  }

  return result;
}

export function highlightKeywords(text: string, keywords: string[]) {
  var regexString = keywords.join('|');
  var regex = new RegExp(regexString, 'gi');
  var highlightedText = text.replace(regex, function(matched){
    return '<span style="color: #267AFF">' + matched + '</span>';
  });
  return highlightedText;
}

export function wait(time: number = 200) {
  return new Promise((resolve, reject) => {
    setTimeout(() => {
      resolve(true);
    }, time)
  })
}

const mobileRegex = /^1[123456789]\d{9}$/
const mobileStarRegex = /(\d{3})\d{4}(\d{4})/;
const regionPhoneStartRegx = /\d{4}$/;
/** 手机号码 中间四位加* */
export function encryptMobile(mobile: string): string {
  const tel = ("" + (mobile || '')).replaceAll(" ", "");
  if (mobileRegex.test(tel)) {
    return tel.replace(mobileStarRegex, "$1****$2")
  } else {
    return tel.replace(regionPhoneStartRegx, "****")
  }
}

export function copyText(text: string) {
  navigator.clipboard.writeText(text).then(() => {
    showToast('已复制到剪切板');
  }).catch(() => {
    showToast('复制失败');
  });
}
